import re

from django.contrib.auth.backends import ModelBackend

from users.models import Userss


def get_user_by_account(account):
    """
    根据帐号获取user对象
    :param account: 账号，可以是用户名，也可以是手机号
    :return: User对象 或者 None
    """
    # print(account)
    try:
        if re.match('^1[3-9]\d{9}$', account):
            # 帐号为手机号
            user = Userss.objects.get(mobile=account)
        else:
            # 帐号为用户名
            user = Userss.objects.get(username=account)
    except Userss.DoesNotExist:
        # print(123)
        return None
    else:
        return user


class UsernameMobileAuthBackend(ModelBackend):
    """
    自定义用户名或手机号认证
    """

    def authenticate(self, request, username=None, password=None, **kwargs):
        user = get_user_by_account(username)
        if user is not None and user.check_password(password) and user.is_authenticated:
            return user
        else:
            return None

        # if request is None:
        #     # 后台登录业务逻辑
        #     try:
        #         # is_superuser:判断用户是否是超级管理员用户
        #         # user = User.objects.get(username=username, is_superuser=True)
        #         #  is_staff:判断是否是后台管理员用户
        #         user = Userss.objects.get(username=username, is_staff=True)
        #     except:
        #         user = None
        # else:
        #     # 前台登录业务逻辑
        #     # 查询用户
        #     user = get_user_by_account(username)
        #         # print(11)
        #         # 如何可以查询到用户，还需要进行密码校验
        #     if user and user.check_password(password):
        #         # 返回user
        #         return user
        #     else:
        #         return None


def jwt_response_payload_handler(token, user=None, request=None):
    """
    自定义jwt认证成功返回数据
    """
    return {
        'token': token,
        'id': user.id,
        'username': user.username
    }